package magicloan.auctionpocket.ui.activity;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Looper;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.immortalviewpager.AutoScrollViewPager;
import com.immortalviewpager.FillingViewsListener;
import com.utils.module.ImgRequestLayout;
import com.utils.module.ScreenUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.logging.Handler;

import magicloan.auctionpocket.R;
import magicloan.auctionpocket.adapter.ImmorVpAdapterMainFg;
import magicloan.auctionpocket.adapter.ProductDetailAdapter;
import magicloan.auctionpocket.bean.ProductDetailBean;
import magicloan.auctionpocket.ui.base.BaseActivity;
import magicloan.auctionpocket.util.UiUtils;

import static magicloan.auctionpocket.R.id.ll_top_container;

/**
 * Created by hechao on 2018/2/2.
 * ac_product_detail_ordershow
 */
public class ProductDetailActivity extends BaseActivity {

    private ProductDetailAdapter mAdapter;
    private ArrayList<ProductDetailBean> mReDateList;
    private ArrayList<ProductDetailBean> mReDateListThird;
    private RecyclerView mRecyclerView;
    private EditText mEditText;
    // 顶部推送控件
    private View ll_product_detail_title_push_total;
    // 商品价格和倒计时控件
    private View rl_product_price_and_time;
    // 判断页面是否Finish了
    private boolean isFinish = false;
    // recyclerView 的LayoutManager
    private LinearLayoutManager layoutManager_right;
    // 需要截取的布局的Y轴坐标
    private int cutLayoutLocationY;
    // title下面的计时布局
    private View rl_product_price_and_time_ac;

    @Override
    protected int setContentView() {
        return R.layout.ac_product_detail;
    }

    @Override
    protected void beforeInitView() {

        mAdapter = new ProductDetailAdapter(mContext, null);
        mAdapter.setOnLoadMoreListener(new MyRequestLoadMoreListener());
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);

        mReDateList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            ProductDetailBean instance = new ProductDetailBean();
            instance.setType(0);
            mReDateList.add(instance);
        }

        mReDateListThird = new ArrayList<>();
        ProductDetailBean instance1 = new ProductDetailBean();
        instance1.setType(1);
        mReDateListThird.add(instance1);

    }

    @Override
    protected void afterInitView() {
        setTitle("商品详情", null);

        // title下面的计时布局
        rl_product_price_and_time_ac = mContentView.findViewById(R.id.rl_product_price_and_time_ac);

        //----RecylerView 第一个
        mRecyclerView = (RecyclerView) mContentView.findViewById(R.id.recylerv);
        layoutManager_right = new LinearLayoutManager(mContext);
        mRecyclerView.setLayoutManager(layoutManager_right);

        mAdapter.addHeaderView(initHeadView());
        mRecyclerView.setAdapter(mAdapter);

        try {
            JSONArray array = new JSONArray(arr);
            setHeadViewData(array);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        //----RecylerView 第一个
        mEditText = (EditText) mContentView.findViewById(R.id.et_num);
        mContentView.findViewById(R.id.tv_sub).setOnClickListener(this);

        initTitlePushUi();
        initListener();

    }

    // 初始化监听事件
    public void initListener() {
        new android.os.Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                int [] locationScreen = {0, 0};
                rl_product_price_and_time.getLocationOnScreen(locationScreen);
                cutLayoutLocationY = locationScreen[1] - UiUtils.dp2px(60);
            }
        }, 200);

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (layoutManager_right.findFirstVisibleItemPosition() == 0) {
                    int scrollDistance = Math.abs(mRecyclerView.getChildAt(0).getTop());
                    if (scrollDistance >= cutLayoutLocationY && cutLayoutLocationY != 0) {
                        if (rl_product_price_and_time_ac.getVisibility() == View.GONE) {
                            rl_product_price_and_time_ac.setVisibility(View.VISIBLE);
                        }
                    } else if (cutLayoutLocationY != 0) {
                        if (rl_product_price_and_time_ac.getVisibility() == View.VISIBLE) {
                            rl_product_price_and_time_ac.setVisibility(View.GONE);
                        }
                    }
                }
            }
        });
    }

    private void initTitlePushUi() {

        // title上的推送控件
        ll_product_detail_title_push_total = mContentView.findViewById(R.id.ll_product_detail_title_push_total);
        ll_product_detail_title_push_total.setAlpha(0);

        new android.os.Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                new Thread() {
                    @Override
                    public void run() {
                        while (!isFinish) {
                            try {
                                final float alpha = ll_product_detail_title_push_total.getAlpha();
                                new android.os.Handler(Looper.getMainLooper()).post(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (alpha == 0) {
                                            titlePushAnimation(0, 1);
                                        } else {
                                            titlePushAnimation(1, 0);
                                        }
                                    }
                                });
                                sleep(3000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }.start();
            }
        }, 3000);

    }

    private class MyRequestLoadMoreListener implements BaseQuickAdapter.RequestLoadMoreListener {
        @Override
        public void onLoadMoreRequested() {

        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.rl_first:
                mViewRule.setVisibility(View.GONE);
                mAdapter.setNewData(mReDateList);
                mAdapter.notifyDataSetChanged();
                break;
            case R.id.rl_second:
                mViewRule.setVisibility(View.GONE);
                mAdapter.setNewData(mReDateListThird);
                mAdapter.notifyDataSetChanged();
                break;
            case R.id.rl_third:
                mViewRule.setVisibility(View.VISIBLE);
                mAdapter.setNewData(null);
                break;
            case R.id.tv_sub:
                showPopUp(mEditText);
                break;
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {

    }

    //-----------HeadView
    private String arr = "[{\"reminder\":\"\",\"rateType\":1,\"obtainTime\":\"10分钟\",\"client\":\"所有\",\"dateTime\":null,\"applyCondition\":\"20-45周岁\",\"show\":1,\"type\":0,\"loanScopeEnd\":20000,\"urlType\":0,\"id\":240,\"rank\":1,\"rate\":\"0.9\",\"description\":\"全自动审核放款，20000元即时到账\",\"loanScopeStart\":1000,\"loanPeriodScopeGrads\":\"1,2,4,6,8,10,12\",\"key\":\"banner_1511175294767\",\"loanPeriodScope\":\"1-12个月\",\"clearForm\":0,\"icon\":\"https:\\/\\/icon.cainiaodk.com\\/1491388278455.png\",\"loanScopeGrads\":\"1000,2000,5000,10000,15000,20000\",\"url0\":\"\",\"labels\":\"申请流程快(109),手续简单(177),快速审核(91),下款神速(71),利率合适(125),额度满意(134)\",\"starPoints\":50,\"image\":\"https:\\/\\/icon.cainiaodk.com\\/\",\"codeType\":1,\"code\":\"var hm=document.createElement('script');hm.src='https:\\/\\/file.cainiaodk.com\\/banner_1509157584295.js?t=1515737928493';var s=document.getElementsByTagName('script')[0];s.parentNode.insertBefore(hm, s);var hm=document.createElement('script');hm.src='https:\\/\\/file.cainiaodk.com\\/ajaxhook.js';var s=document.getElementsByTagName('script')[0];s.parentNode.insertBefore(hm, s);\",\"url\":\"http:\\/\\/m.haomoney.com\\/activity\\/reg\\/register.html?utm_source=wap_cainiaodaikuan3\",\"sign\":\"1\",\"needDatum\":\"身份证\",\"commentNum\":128,\"applyNum\":453789,\"labels1\":\"额度小,审核时间长,利息贵,放款慢,联系不到客服,看征信\",\"labels0\":\"申请流程快,手续简单,快速审核,下款神速,利率合适,额度满意\",\"loanScope\":\"1000-20000\",\"tittle\":\"小树时代\",\"explain\":\"1、无抵押、无担保，纯信用贷款； \\n2、全自动审核放款，即时到账；\\n3、按天计息，一次审核，循环提现，定期提额；\\n4、支持部分还款，容时还款，提前还款，不需支付额外费用\",\"productName\":\"\",\"channel\":\"\",\"handler\":{}},{\"reminder\":\"1\",\"rateType\":0,\"obtainTime\":\"10分钟\",\"client\":\"所有\",\"dateTime\":null,\"applyCondition\":\"1\",\"show\":1,\"type\":0,\"loanScopeEnd\":5000,\"urlType\":1,\"id\":182,\"rank\":2,\"rate\":\"1\",\"description\":\"1\",\"loanScopeStart\":3000,\"loanPeriodScopeGrads\":\"1\",\"key\":\"banner_1502426806666\",\"loanPeriodScope\":\"6-12个月\",\"clearForm\":0,\"icon\":\"https:\\/\\/icon.cainiaodk.com\\/1508911852214.png\",\"loanScopeGrads\":\"1\",\"url0\":\"\",\"labels\":\"1\",\"starPoints\":1,\"image\":\"https:\\/\\/icon.cainiaodk.com\\/1505980935312.png\",\"codeType\":1,\"code\":\"\",\"url\":\"http:\\/\\/m.haomoney.com\\/activity\\/reg\\/register.html?utm_source=wap_cainiaodaikuan\",\"sign\":\"1\",\"needDatum\":\"1\",\"commentNum\":4,\"applyNum\":1,\"labels1\":\"1\",\"labels0\":\"1\",\"loanScope\":\"3000-5000\",\"tittle\":\"天神贷\",\"explain\":\"1\",\"productName\":\"天神贷\",\"channel\":\"\",\"handler\":{}},{\"reminder\":\"1\",\"rateType\":0,\"obtainTime\":\"1\",\"client\":\"所有\",\"dateTime\":null,\"applyCondition\":\"1\",\"show\":1,\"type\":0,\"loanScopeEnd\":0,\"urlType\":0,\"id\":110,\"rank\":3,\"rate\":\"1\",\"description\":\"1\",\"loanScopeStart\":0,\"loanPeriodScopeGrads\":\"1\",\"key\":\"banner_8ee039\",\"loanPeriodScope\":\"6-12个月\",\"clearForm\":1,\"icon\":\"https:\\/\\/icon.cainiaodk.com\\/1502943433196.png\",\"loanScopeGrads\":\"1\",\"url0\":\"\",\"labels\":\"1\",\"starPoints\":0,\"image\":\"https:\\/\\/icon.cainiaodk.com\\/1504496036288.png\",\"codeType\":1,\"code\":\"\",\"url\":\"http:\\/\\/wap.apass.vcash.cn\\/#\\/downAppReg?channel=cndk\",\"sign\":\"1\",\"needDatum\":\"1\",\"commentNum\":5,\"applyNum\":1,\"labels1\":\"1\",\"labels0\":\"1\",\"loanScope\":\"1000-20000\",\"tittle\":\"安家趣花\",\"explain\":\"1\",\"productName\":\"安家趣花\",\"channel\":\"\",\"handler\":{}}]";

    private AutoScrollViewPager mVp_top_mainfg;
    private LinearLayout mLL_top_container;
    private RelativeLayout mRl;
    private ImmorVpAdapterMainFg mTopVpAdapter;
    private View mViewRule;

    private View initHeadView() {
        View headV = View.inflate(mActivity, R.layout.ac_product_recyler_headview, null);
        //顶部VP
        mVp_top_mainfg = (AutoScrollViewPager) headV.findViewById(R.id.vp_top_mainfg);
        mLL_top_container = (LinearLayout) headV.findViewById(ll_top_container);
        mRl = (RelativeLayout) headV.findViewById(R.id.rl);
        mViewRule = headV.findViewById(R.id.ll_rule);

        mTopVpAdapter = new ImmorVpAdapterMainFg(mContext);

        // 获取需要截取的UI所在的坐标位置
        rl_product_price_and_time = headV.findViewById(R.id.rl_product_price_and_time);

        headV.findViewById(R.id.rl_first).setOnClickListener(this);
        headV.findViewById(R.id.rl_second).setOnClickListener(this);
        headV.findViewById(R.id.rl_third).setOnClickListener(this);

        return headV;
    }

    public void setHeadViewData(final JSONArray mTopUrlArray) {
        //顶部ViewPager
        if (mTopUrlArray != null && mTopUrlArray.length() > 0) {
            mVp_top_mainfg.setAdapter(mTopVpAdapter);
            mTopVpAdapter.setBtmCount(mLL_top_container,
                    R.layout.single_circleimg, mTopUrlArray.length(), R.mipmap.vp_choose,
                    R.mipmap.vp_unchoose, ScreenUtils.getScreenHeight(mContext) / 100);
            mTopVpAdapter.initViewList(mTopUrlArray.length(), R.layout.vp_item_banner_mainfg,//topUrlArray.length()
                    new FillingViewsListener() {

                        @Override
                        public void fillingView(View view, int position) {
                            final JSONObject obj = mTopUrlArray.optJSONObject(position);
                            ImageView img = (ImageView) view.findViewById(R.id.auto_vp_img);
                            ImgRequestLayout.requestLayout(mRl, mContext, 161.0f, 375.0f);
                            Glide.with(mContext)
                                    .load(obj.optString("image"))
                                    .placeholder(R.mipmap.ic_launcher)
                                    .crossFade()
                                    .into(img);
                        }

                    });
            mTopVpAdapter.notifyDataSetChanged();
            mVp_top_mainfg.setCurrentItem(1);
            mVp_top_mainfg.setInterval(2500);
            mVp_top_mainfg.startAutoScroll();
        }

    }

    private void showPopUp(View v) {
        LinearLayout layout = new LinearLayout(this);
        layout.setBackgroundColor(Color.GRAY);
        TextView tv = new TextView(this);
        tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        tv.setText("I'm a pop -----------------------------!");
        tv.setTextColor(Color.WHITE);
        layout.addView(tv);

        PopupWindow popupWindow = new PopupWindow(layout, 120, 120);

        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());

        int[] location = new int[2];
        v.getLocationOnScreen(location);

        popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0], location[1] - popupWindow.getHeight());
    }

    public void titlePushAnimation(final float startAlapha, final float endAlpha) {
        ll_product_detail_title_push_total.setVisibility(View.VISIBLE);
        ValueAnimator valueAnimator = ObjectAnimator.ofFloat(startAlapha, endAlpha);
        valueAnimator.setDuration(500);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float alapha = (float) animation.getAnimatedValue();
                ll_product_detail_title_push_total.setAlpha(alapha);
            }
        });
        valueAnimator.start();
    }

    @Override
    protected void onDestroy() {
        isFinish = true;
        super.onDestroy();
    }
}
